package icu.javayanglei.file.controller

import cn.hutool.core.convert.Convert
import cn.hutool.core.io.FileUtil
import icu.javayanglei.file.service.IndexService
import icu.javayanglei.file.util.ServletUtil
import icu.javayanglei.file.vo.CutFileVo
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.multipart.MultipartFile
import java.io.IOException
import jakarta.servlet.http.HttpServletResponse


@RestController
class IndexController @Autowired constructor(private val service: IndexService) {

    /**
     * @param path     指想要下载的文件的路径
     * @param response 响应
     */
    @PostMapping("/download")
    @Throws(IOException::class)
    fun download(@RequestParam("path") path: String, response: HttpServletResponse) {
        ServletUtil.write(response, FileUtil.file(path));
    }

    @PostMapping("/upload")
    fun uploadFile(
        @RequestParam("file") file: MultipartFile, @RequestParam(name = "fileSize", required = false) fileSize: Int
    ): CutFileVo {
        val size = Convert.toInt(fileSize, 40)
        val touch = service.multipartFileToFile(file);
        return service.cutFile(touch, size)
    }

    @PostMapping("/merge")
    fun merge(
        @RequestParam("files") files: Array<MultipartFile>,
        response: HttpServletResponse
    ) {
        val mergeFile = service.mergeFile(files)
        ServletUtil.write(response, FileUtil.file(mergeFile));
    }

}
